package extraction.html.chase;

import org.htmlparser.Parser;
import org.htmlparser.Node;
import org.htmlparser.util.ParserException;
import org.htmlparser.util.NodeList;

import java.util.ArrayList;
import java.util.List;

import extraction.html.ExtractionUtils;

/**
 * @author Nathan Petryk (nathanp@indeed.com)
 */
public class ChaseAccountScreenParser {

    private ChaseAccountScreenParser() {}

    public static AccountSummary extractAccountSummary(String in) throws ParserException {
        Parser parser = new Parser(in);
        NodeList nodes = parser.parse(null);

        List<Node> temp = new ArrayList<Node>();

        Node accountTable, accountRow, accountAnchor;

        ExtractionUtils.findWith(temp, "summary=\"bank account information\"", nodes.toNodeArray());
        accountTable = temp.get(0);
        temp.clear();

        ExtractionUtils.getNodesOfType("tr", 1, accountTable, temp);
        accountRow = temp.get(2);
        temp.clear();

        ExtractionUtils.getNodesOfType("a", 3, accountRow, temp);
        accountAnchor = temp.get(0);
        temp.clear();

        ExtractionUtils.getNodesOfType("td", 1, accountRow, temp);

        String aIntlTxt = accountAnchor.getText();
        String anchorText = accountAnchor.getFirstChild().getText().replaceAll("&nbsp;", "|");
        String presentBalance = temp.get(2).getFirstChild().getText();
        String availableBalance = temp.get(3).getFirstChild().getText();

        AccountSummary summ = new AccountSummary(
                -1,
                anchorText.substring(0, anchorText.indexOf("|")),
                Integer.parseInt(anchorText.substring(anchorText.indexOf("(...")+4, anchorText.indexOf(")"))),
                Double.parseDouble(presentBalance.replaceAll("[^0-9\\.]", "")),
                Double.parseDouble(availableBalance.replaceAll("[^0-9\\.]", "")),
                aIntlTxt.substring(aIntlTxt.indexOf("href=\"")+6, aIntlTxt.indexOf("\"", aIntlTxt.indexOf("href=\"")+6))
        );

        System.out.println(summ.accountName+", "+summ.lastFourDigits+", "+summ.transactionURL+", "+summ.presentBalance+", "+summ.availableBalance);

        return summ;
    }

    public static void main(String[] args) throws ParserException {
        ChaseAccountScreenParser.extractAccountSummary("//home//nathanp//jtml//sample//accounts.html");
    }
}
